package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.List;

@DubboService
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据用户信息，随机得到一条语音信息
     * @param userInfo
     * @return
     */
    @Override
    public Voice findOne(UserInfo userInfo, List readList) {

        //2 随机查询Voice表 以及 排除性别为当前登录用户相反的性别
        //2.1 构造条件  toUserId=当前用户id  userId排除likeUserIds（userId not in(1,2,3)）
        // 只随机查询一条记录
        int count = 1;
        Criteria criteria = Criteria.where("gender").nin(userInfo.getGender());
        if(CollectionUtils.isNotEmpty(readList)) {
            criteria.and("id").nin(readList);
        }
        //2.2 随机取出1条推荐语音信息
        TypedAggregation<Voice> voiceTypedAggregation = TypedAggregation.newAggregation(Voice.class, Aggregation.match(criteria), Aggregation.sample(count));
        AggregationResults<Voice> aggregate = mongoTemplate.aggregate(voiceTypedAggregation, Voice.class);

        return aggregate.getUniqueMappedResult();
    }
    /**
     * 桃花传音:发送语音
     */
    @Override
    public void add(Long userId, String voiceUrl, String gender) {
        Voice voice = new Voice();
        voice.setCreateDate(System.currentTimeMillis());
        voice.setUserId(userId);
        voice.setGender(gender);
        voice.setSoundUrl(voiceUrl);
        mongoTemplate.insert(voice);
    }
}
